package com.jsgt.greekfire.ui.gfc

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.common.util.CountDownTimerUtils
import com.jsgt.greekfire.common.util.MD5Util
import com.jsgt.greekfire.event.ExitEvent
import com.jsgt.greekfire.factory.CoinGFCModelFactory
import com.jsgt.greekfire.viewmodel.CoinCurrencyViewModel
import kotlinx.android.synthetic.main.activity_buy_gfc_coin.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.backgroundColor

class BuyGFCCoinActivity : BaseActivity(), TextWatcher {
    var tvTitle: TextView? = null
    var title_layout: RelativeLayout? = null
    private var flag = false
    var bundle: Bundle? = null
    var gfc: String? = null
    var usdt: String? = null
    var dealAmount: String? = null
    var guid: String? = null
    var back: ImageView? = null
    private val DECIMAL_DIGITS = 4 //小数的位数

    override fun getLayoutId(): Int = R.layout.activity_buy_gfc_coin
    private val coinCurrencyViewModel: CoinCurrencyViewModel by lazy {
        ViewModelProvider(
            this,
            CoinGFCModelFactory()
        ).get(CoinCurrencyViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bundle = intent.extras
        gfc = bundle?.getString("gfc")
        usdt = bundle?.getString("usdt")
        dealAmount = bundle?.getString("dealAmount")
        guid = bundle?.getString("guid")
    }

    override fun onStart() {
        super.onStart()
        if (!TextUtils.isEmpty(dealAmount)) {
            var num = dealAmount!!.toFloat() * 7
            tvusdt?.text = "¥$num"
        }
    }

    override fun main() {
        initView()

        tvWholeNum.setOnClickListener { v ->
            etNum?.setText(gfc)
        }
        tvAmount.setOnClickListener { v ->
            etAmount?.setText(usdt)
        }


        btnBuy.setOnClickListener { v ->
            //ToastUtils.show("购买")
            coinCurrencyViewModel.getAddOrder(
                etNum?.text.toString().trim(),
                guid!!,
                MD5Util.getMD5(etPwd?.text.toString().trim())
            )
        }

        coinCurrencyViewModel.AddOrderData.observe(this, Observer {
            ToastUtils.show("已提交")
            finish()
        })
        coinCurrencyViewModel.errorLiveData.observe(this, Observer {
            ToastUtils.show(it.toString())

        })

    }


    private fun initView() {
        tvTitle = findViewById(R.id.title_tv)
        back = findViewById(R.id.back)
        title_layout = findViewById(R.id.title_layout)
        tvTitle?.text = "出售GFC"
        title_layout?.backgroundColor = resources.getColor(R.color.pllo_3B476F)

//        etNum.setFilters(arrayOf<InputFilter>(DecimalDigitsInputFilter(4)))
//        etAmount.setFilters(arrayOf<InputFilter>(DecimalDigitsInputFilter(4)))


        val mCountDownTimerUtils = CountDownTimerUtils(tvSec!!, 60000, 1000, 0)
        mCountDownTimerUtils.start()

        etNum.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.toString().contains(".")) {
                    if (s.length - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        var s = s.toString().subSequence(
                            0,
                            s.toString().indexOf(".") + DECIMAL_DIGITS + 1
                        );
                        etNum.setText(s);
                        etNum.setSelection(s.length);
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    var s = "0" + s;
                    etNum.setText(s);
                    etNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                    && s.toString().trim().length > 1
                ) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etNum.setText(s.subSequence(0, 1));
                        etNum.setSelection(1);
                        return;
                    }
                }

            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (flag) {
                    return;
                }
                flag = true;

                //功能实现部分
                btnBuy?.isEnabled =
                    etNum.text.toString().trim().isNotEmpty() && etAmount.text.toString()
                        .trim().isNotEmpty() && etPwd.text.toString().trim().isNotEmpty()
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    var num = s.toString().trim().toFloat()
                    var p = dealAmount!!.toFloat()
                    var n = num * p
                    etAmount?.setText(n.toString())
                } else {
                    etAmount?.setText("")
                }
                flag = false;
            }
        })

        etAmount.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(
                s: CharSequence, start: Int, before: Int,
                count: Int
            ) {
                if (s.toString().contains(".")) {
                    if (s.length - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        var s = s.toString().subSequence(
                            0,
                            s.toString().indexOf(".") + DECIMAL_DIGITS + 1
                        );
                        etAmount.setText(s);
                        etAmount.setSelection(s.length);
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    var s = "0" + s;
                    etNum.setText(s);
                    etNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                    && s.toString().trim().length > 1
                ) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etAmount.setText(s.subSequence(0, 1));
                        etAmount.setSelection(1);
                        return;
                    }
                }
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (flag) {
                    return;
                }
                flag = true;
                btnBuy?.isEnabled =
                    etNum.text.toString().trim().isNotEmpty() && etAmount.text.toString()
                        .trim().isNotEmpty() && etPwd.text.toString().trim().isNotEmpty()
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    var num = s.toString().trim().toFloat()
                    var p = dealAmount!!.toFloat()
                    var n = num / p
                    etNum?.setText(n.toString())
                } else {
                    etNum?.setText("")
                }
                flag = false;
            }
        })
        etPwd.addTextChangedListener(this)
        back?.setOnClickListener { v ->
            finish()
            coinCurrencyViewModel.getotcAdStateData(guid!!, "0")
        }

    }

    override fun afterTextChanged(s: Editable?) {

    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        btnBuy?.isEnabled = etNum.text.toString().trim().isNotEmpty() && etAmount.text.toString()
            .trim().isNotEmpty() && etPwd.text.toString().trim().isNotEmpty()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onExit(e: ExitEvent) {
        coinCurrencyViewModel.getotcAdStateData(guid!!, "0")
        //购买倒计时结束 退出界面
        finish()
    }

    override fun onBackPressed() {
        coinCurrencyViewModel.getotcAdStateData(guid!!, "0")
        super.onBackPressed()
    }


}